package com.giveu.signature.module.template.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.giveu.common.exception.ResultRuntimeException;
import com.giveu.common.page.PageModel;
import com.giveu.common.page.QueryMap;
import com.giveu.common.service.RedisService;
import com.giveu.signature.bean.TemplateHtmlParam;
import com.giveu.signature.bean.TemplateHtmlParam.SignatureConf;
import com.giveu.signature.bean.TemplateHtmlParam.TemplateParam;
import com.giveu.signature.bean.TemplateHtmlParam.TemplateSign;
import com.giveu.signature.common.util.BeanUtil;
import com.giveu.signature.common.util.MapperUtil;
import com.giveu.signature.config.FeignProperties;
import com.giveu.signature.conts.RedisKey;
import com.giveu.signature.module.template.mapper.SignTemplateHtmlMapper;
import com.giveu.signature.module.template.mapper.SignTemplateHtmlParamMapper;
import com.giveu.signature.module.template.mapper.SignTemplateParamMapper;
import com.giveu.signature.module.template.mapper.SignTemplateRelationMapper;
import com.giveu.signature.module.template.model.SignTemplateHtml;
import com.giveu.signature.module.template.model.SignTemplateHtmlParam;
import com.giveu.signature.module.template.model.SignTemplateParam;
import com.giveu.signature.module.template.model.SignTemplateRelation;
import com.giveu.signature.module.template.service.SignTemplateHtmlService;
@Service
public class SignTemplateHtmlServiceImpl implements SignTemplateHtmlService {
	
	private static final Logger log = LoggerFactory.getLogger(SignTemplateHtmlServiceImpl.class);
	
	@Autowired
	RedisService redisService;
	@Autowired
	SignTemplateHtmlMapper signTemplateHtmlMapper;
	@Autowired
	FeignProperties feignProperties;
	@Autowired
	SignTemplateHtmlParamMapper signTemplateHtmlParamMapper;
	@Autowired
	SignTemplateParamMapper signTemplateParamMapper;
	@Autowired
	SignTemplateRelationMapper signTemplateRelationMapper;
	
	@Override
	public SignTemplateHtml get(Long id) {
		SignTemplateHtml entity = signTemplateHtmlMapper.selectByPrimaryKey(id);
		if(entity==null){
			return null;
		}
		if(StringUtils.isNotBlank(entity.getFastUrl())){
			entity.setFastPath(feignProperties.getFastdfsUrl()+entity.getFastUrl());
		}
		setParamInfo(entity);
		entity.setSignList(signTemplateRelationMapper.getSignList(id));
		return entity;
	}

	private void setParamInfo(SignTemplateHtml entity) {
		List<SignTemplateParam> list = signTemplateParamMapper.selectParamByHtmlId(entity.getId());
		if(list==null||list.isEmpty()){
			return;
		}
		entity.setParamIds(list.stream().map(SignTemplateParam::getId).collect(Collectors.toList()));
		entity.setParamList(list);
	}

	@Override
	public PageInfo<SignTemplateHtml> listByPage(QueryMap<SignTemplateHtml> queryMap) {
		PageModel page = queryMap.getPage();
        PageHelper.startPage(page);
        List<SignTemplateHtml> list = new ArrayList<>();
        try {
            list = signTemplateHtmlMapper.selectList(queryMap.getEntity());
            for (SignTemplateHtml signTemplateHtml : list) {
            	signTemplateHtml.setFastPath(feignProperties.getFastdfsUrl()+signTemplateHtml.getFastUrl());
			}
        } catch (Exception e) {
        	throw new ResultRuntimeException("数据查询异常",e);
        }
        return new PageInfo<>(list);
	}

	
	@Override
	@Transactional
	public void save(SignTemplateHtml entity) {
		checkTemplate(entity);
		if(StringUtils.isNotBlank(entity.getParamIdstr())){
			List<Long> pList = new ArrayList<>();
			for (String str : entity.getParamIdstr().split(",")) {
				pList.add(Long.parseLong(str));
			}
			entity.setParamIds(pList);
		}
		if(entity.getId()==null){
			signTemplateHtmlMapper.insertSelective(entity);
		}else{
			signTemplateHtmlMapper.updateByPrimaryKeySelective(entity);
		}
		if(entity.getParamIds()!=null&&!entity.getParamIds().isEmpty()){
			SignTemplateHtmlParam del = new SignTemplateHtmlParam();
			del.setHtmlId(entity.getId());
			signTemplateHtmlParamMapper.delete(del);
			for (Long pid : entity.getParamIds()) {
				SignTemplateHtmlParam ins = new SignTemplateHtmlParam();
				ins.setHtmlId(entity.getId());
				ins.setParamId(pid);
				signTemplateHtmlParamMapper.insertSelective(ins);
			}
		}
		if(entity.getSignList()!=null&&!entity.getSignList().isEmpty()){
			SignTemplateRelation del = new SignTemplateRelation();
			del.setHtmlId(entity.getId());
			signTemplateRelationMapper.delete(del);
			for (SignTemplateRelation rel : entity.getSignList()) {
				rel.setId(null);
				rel.setHtmlId(entity.getId());
				signTemplateRelationMapper.insertSelective(rel);
			}
		}
		if(entity.getTempStatus()!=null&&entity.getTempStatus()==1){
			setCache(entity);
		}
	}

	private void checkTemplate(SignTemplateHtml entity) {
		if(!entity.isModify()){
			SignTemplateHtml record = new SignTemplateHtml();
			record.setTempCode(entity.getTempCode());
			record.setTempVersion(entity.getTempVersion()==null?1:entity.getTempVersion());
			SignTemplateHtml res = MapperUtil.get(signTemplateHtmlMapper, record);
			if(res!=null){
				if(res.getId()!=entity.getId()){
					throw new RuntimeException("模板编码存在重复");
				}
			}
		}
	}

	private void setCache(SignTemplateHtml entity) {
		String key = entity.getTempCode()+":v"+entity.getTempVersion();
		TemplateHtmlParam tp = new TemplateHtmlParam();
		tp.setTempKey(key);
		tp.setGenModel(entity.getGenModel());
		tp.setHtml(entity.getHtmlText());
		tp.setHtmlId(entity.getId());
		tp.setFastPath(feignProperties.getFastdfsUrl()+entity.getFastUrl());
		List<SignTemplateParam> pList = signTemplateParamMapper.selectParamByHtmlId(entity.getId());
		if(pList!=null&&!pList.isEmpty()){
			List<TemplateParam> templateParams = new ArrayList<>();
			for (SignTemplateParam param : pList) {
				TemplateParam np = new TemplateParam();
				BeanUtil.copyProperties(param, np);
				templateParams.add(np);
			}
			tp.setTemplateParams(templateParams);
		}
		List<SignTemplateRelation> sList = signTemplateRelationMapper.getSignByHtmlId(entity.getId());
		if(sList!=null&&!sList.isEmpty()){
			List<TemplateSign> templateSigns = new ArrayList<>();
			for (SignTemplateRelation sign : sList) {
				TemplateSign np = new TemplateSign();
				BeanUtil.copyProperties(sign, np);
				SignatureConf sconf = new SignatureConf();
				BeanUtil.copyProperties(sign.getSignConfig(), sconf);
				sconf.setImageUrl(feignProperties.getFastdfsUrl()+sconf.getImageUrl());
				sconf.setKeystoreUrl(feignProperties.getFastdfsUrl()+sconf.getKeystoreUrl());
				np.setSignConf(sconf);
				templateSigns.add(np);
			}
			tp.setTemplateSigns(templateSigns);
		}
		redisService.setMap(RedisKey.SIGN_TEMPLATE_MAX_VERSION_MAP, entity.getTempCode(), String.valueOf(entity.getTempVersion()));
		redisService.setMap(RedisKey.SIGN_TEMPLATE_MAP,key, JSON.toJSONString(tp));
	}

	@Override
	public void delete(SignTemplateHtml entity) {
		signTemplateHtmlMapper.deleteByPrimaryKey(entity.getId());
	}
	
}
